from TinyShop17.CASE import LoginTinyShop
import re


class CreatOrder:
    def __init__(self, num=1, goodsid=69, addressid=2, paymentid=1, invicetype=0, username='253775405@qq.com',
                 password='yang130740', url='http://192.168.10.139/ty17/TinyShop_v1.7'):
        self.session, result = LoginTinyShop.Login(username, password).start()
        print(result)
        self.url = url
        self.num = num
        self.goodsid = goodsid
        self.addressid = addressid
        self.paymentid = paymentid
        self.invicetype = invicetype

    def addGoods(self):  # 选了商品进入订单支付页面
        url = '%s/index.php?con=index&act=cart_add' % self.url
        data = {
            'num': self.num,  # 几件
            'id': self.goodsid  # 商品id
        }
        self.session.post(url, data=data)

    def getToken(self):
        url = '%s/index.php?con=simple&act=order' % self.url
        html = self.session.get(url).text
        passent = re.compile(r"<input type='hidden' name='tiny_token_order' value='(.*)'/>")
        self.tiny_token_order = passent.findall(html)[0]

    def payGoods(self):
        url = '%s/index.php?con=simple&act=order_act' % self.url
        data = {
            'address_id': self.addressid,  # 收货地址ID
            'payment_id': self.paymentid,  # 支付方式ID
            'invoice_type': self.invicetype,  # 不打印发票
            'tiny_token_order': self.tiny_token_order
        }
        html = self.session.post(url, data=data).text
        passent = re.compile('</i>(.*) &nbsp;')
        self.content = passent.findall(html)[0]
        if len(self.content) > 0:
            self.res = '订单创建成功  订单编号：%s' % self.content
        else:
            self.res = '订单创建失败'

    def start(self):
        try:
            self.addGoods()
            self.getToken()
            self.payGoods()
        except Exception:
            self.res = '订单创建失败'
        return self.res


if __name__ == "__main__":
    CreatOrder().start()
